package baseFx.tests.database.jdbc;

import baseFx.database.Sql;
import baseFx.database.SqlParam;
import baseFx.tests.database.MockJDBCSql;
import org.junit.Assert;
import org.junit.Test;

public class AbstractJDBCSqlTests {
    @Test
    public void 集合类型参数值的自动展开() {
        Sql sql = new MockJDBCSql();
        SqlParam param = new SqlParam();
        sql.eventBefore().add((s, e) -> {
            param.command = e.param.command;
            param.args.putAll(e.param.args);
        });
        sql.query("id in #id and name=#name and id in #id", new Object() {
            public String name = "abc";
            public Integer[] id = {1, 2, 3};
        });
        Object[] values = param.args.values().toArray();
        Assert.assertEquals("id in (?,?,?) and name=? and id in (?,?,?)", param.command);
        Assert.assertEquals(7, param.args.size());
        Assert.assertEquals(1, values[0]);
        Assert.assertEquals(2, values[1]);
        Assert.assertEquals(3, values[2]);
        Assert.assertEquals("abc", values[3]);
        Assert.assertEquals(1, values[4]);
        Assert.assertEquals(2, values[5]);
        Assert.assertEquals(3, values[6]);

    }

    @Test
    public void 具名参数的使用() {
        Sql sql = new MockJDBCSql();
        SqlParam param = new SqlParam();
        sql.eventBefore().add((s, e) -> {
            param.command = e.param.command;
            param.args.putAll(e.param.args);
        });
        sql.query("id=#id", new Object() {
            public int id = 10;
        });
        Assert.assertEquals(param.command, "id=?");
        Object[] values = param.args.values().toArray();
        Assert.assertEquals(values[0], 10);
    }

    @Test
    public void 参数顺序会自动调整到和SQL中定义时一致() {
        Sql sql = new MockJDBCSql();
        SqlParam param = new SqlParam();
        sql.eventBefore().add((s, e) -> {
            param.command = e.param.command;
            param.args.putAll(e.param.args);
        });
        sql.query("id=#id and name=#name and age>#age", new Object() {
            public String name = "abc";
            public int age = 60;
            public int id = 10;
        });
        Object[] values = param.args.values().toArray();
        Assert.assertEquals(param.command, "id=? and name=? and age>?");
        Assert.assertEquals(values[0], 10);
        Assert.assertEquals(values[1], "abc");
        Assert.assertEquals(values[2], 60);
    }
}
